package www.woniuxy.com.class112.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import www.woniuxy.com.class112.annotation.RequiredPermission;
import www.woniuxy.com.class112.exception.PermissionException;
import www.woniuxy.com.class112.service.PermissionService;
import www.woniuxy.com.class112.util.JwtUtil;
import www.woniuxy.com.class112.util.RedisKeyUtil;
import www.woniuxy.com.class112.util.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    @Resource
    private PermissionService permissionService;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1排除OPTIONS请求
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true;
        }
        //2获取当前请求需要执行的控制器方法
        HandlerMethod h =  (HandlerMethod) handler;
        RequiredPermission annotation = h.getMethod().getAnnotation(RequiredPermission.class);
        if (annotation==null){
            //说明该方法无需权限可直接运行
            return  true;
        }
        String requiredPermission = annotation.value();
        String token = request.getHeader("token");
        //解析出token用户的ID
        Integer userId=Integer.parseInt( JwtUtil.parseToken(token).get("userId").toString());
        List<String> list = redisUtil.getList(RedisKeyUtil.USER_PERMISSIONS_LIST(userId));
        if (!list.contains(requiredPermission)){
            throw new PermissionException();
        }
        return true;
    }
}
